/**
 * Created with IntelliJ IDEA.
 * User: zzl
 * Date: 12-12-17
 * To change this template use File | Settings | File Templates.
 */
(function ($, global, undefined) {

    var $htmlTester;

    $(function () {

        var style = 'position: absolute; top:-1024px;white-space:pre; overflow: visible;';
        $htmlTester = $('<div class="htmlTester" style="' + style + '"></div>');
        $htmlTester.appendTo($(document.body));

    });

    var undecorated = {};

    undecorated.measure = function (refEl, text) {

        var styles = ['padding', 'fontFamily', 'fontSize'];
        for (var n = 0; n < styles.length; n++) {
            var style = styles[n];
            $htmlTester.css(style, refEl.css(style));
        }
        if(!text) {
            $htmlTester.html(refEl.html());
        }
        else if (jsex.indexOf(text, '<') == -1) {
            $htmlTester.text(text);
        }
        else {
            $htmlTester.html(text);
        }
        return {
            width: $htmlTester.width(),
            height: $htmlTester.height()
        }
    };

    undecorated.htmlToPlainText = function (html) {
        if (jsex.indexOf(html, '<') == -1 &&
            jsex.indexOf(html, '&') == -1) {
            return html;
        }
        html = html.replace(/<br\/?>/ig, '`n');
        $htmlTester.html(html);
        var text = $htmlTester.text();
        text = text.replace(/`n/g, '\n');
        return text;
    };

    undecorated.plainTextToHtml = function (text, urlAware) {
        var html = text.replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\n/g, '<br/>');
        if (urlAware && jsex.indexOf(html, 'http') != -1) {
            var r = /(https?:\/\/[^ ]+[^ ,.])/ig;
            html = text.replace(r, "<a href=\"$1\">$1</a>");
        }
        return html;
    };

    undecorated.keydownInterceptors = [];
    undecorated.keydownIntercepted = false;

    undecorated.interceptKeydown = function(e) {
        undecorated.keydownIntercepted = false;
        var interceptors = undecorated.keydownInterceptors;
        for(var n = 0; n < interceptors.length; n++) {
            if(interceptors[n](e)) {
                e.stopImmediatePropagation();
                e.preventDefault();
//                undecorated.keydownIntercepted = true;
                break;
            }
        }
    };

    global.undecorated = undecorated;

})(jQuery, window);